package com.shadow.study.shiro.controller;

import com.shadow.study.common.R;
import com.shadow.study.shiro.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class LocalLoginController {

    /**
     * 登录.
     */
    @PostMapping("login")
    public R login(final LoginUser loginUser) {
        String account = loginUser.getName();
        String password = loginUser.getPassword();
        if (StringUtils.isBlank(account)) {
            return R.fail("用户名为空");
        }
        if (StringUtils.isBlank(password)) {
            return R.fail("密码为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return R.fail("未知账户");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return R.fail("密码不正确");
        } catch (LockedAccountException e) {
            e.printStackTrace();
            return R.fail("账户已锁定");
        } catch (ExcessiveAttemptsException e) {
            e.printStackTrace();
            return R.fail("用户名或密码错误次数过多");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return R.fail("用户名或密码不正确");
        }

        if (subject.isAuthenticated()){
            return R.success().put(R.DATA, "/index");
        }
        token.clear();
        return R.fail("登录失败");
    }
}
